package com.codefish.codefishseckill.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * redis配置
 *
 * @author codefish
 * @version 1.0
 * @date 2022/07/06 下午 02:46
 */
@Configuration
public class RedisConfig {

    @Bean
    RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        //key序列化
        template.setKeySerializer(new StringRedisSerializer());
        //value序列化
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //hash类型key序列化
        template.setHashKeySerializer(new StringRedisSerializer());
        //hash类型value系列化
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //注入连接工厂
        template.setConnectionFactory(factory);
        return template;
    }

    @Bean
    DefaultRedisScript<Boolean> delLockRedisScript(){
        DefaultRedisScript<Boolean> script = new DefaultRedisScript<>();
        script.setLocation(new ClassPathResource("unlock.lua"));
        script.setResultType(Boolean.class);
        return script;
    }

    @Bean
    DefaultRedisScript<Long> countDownStockRedisScript(){
        DefaultRedisScript<Long> script = new DefaultRedisScript<>();
        script.setLocation(new ClassPathResource("stock.lua"));
        script.setResultType(Long.class);
        return script;
    }

}
